define(function(require, exports, module){
	var A = require("resource/js/component/ajax.js");
	var C = require("resource/js/config/const.js");
	var url = require("resource/js/component/urlTool.js");
	var Obj = window.loadI18n('base/easyutil');
	exports.ajaxDataGrid = function(config){
		var conf = {
				fitColumns:true,
				singleSelect:false,
				striped:true,
				autoRowHeight:false,
				fit: true,
				eid:"",
				url:"",
				pagesize:15,
				pageNo:1,
				total:0,
				autoLoad:true,//自动调用初始化页面数据
				args:{},
				//ajax创建可以动态增加一部分属性
				ajaxCreater:function(){return A.init();},
				//提交参数过滤  参数 表单字段序列化完的json类型数据  返回值是真正提交的数据
				argsFilter:function(args){return args;},
				ajaxHandler:function(args,url,upfun){
					this.ajaxCreater().success(function(code,msg,data){
						upfun(code,msg,data);
					}).error(function(code,msg,data){
						if(msg!=''){
							using(['messager'],function(){
								$.messager.alert(C.MESSAGE.MSGTITLE,msg);
							});
						}
						upfun(code,msg,data);
					}).post(url,this.argsFilter(args));
				},
				loadMsg:Obj.get('base.common.easyutil.Loading'),
				pagination:true,
				selectPage:function(no,size){},
				frozenColumns:[[
				                {field:'ck',checkbox:true}
                              ]],
                //noheader:true,
                check:true,
                rownumbers:true,
		};
		for(var key in config){
			conf[key] = config[key];
		}
		conf.ajaxurl = conf.url;
		conf.url=undefined;
		conf.onLoadSuccess = function(data){
			var width = $(".datagrid-view2").width();
        	$(".datagrid-view2").find("table").width(width);
        	if($.isFunction(config.onLoadSuccess)){
				config.onLoadSuccess(data);
			}
		}
		if(typeof conf.eid=="string"){
			this.dg = $("#"+conf.eid);
		}else{
			this.dg = conf.eid;
		}
		if(!conf.check){
			conf.frozenColumns = undefined;
		}
		/**
		 * 初始化分页插件
		 * */
		this.initPage = function(){
			if(conf.args==undefined)
				conf.args = {};
			$(this.dg).datagrid(conf);
			conf.url = conf.ajaxurl;
			if(conf.pagination){
				var tmpFun = this.loadUrlData;
				$(this.dg.datagrid('getPager')).pagination({
					total: conf.total,
					pageNumber: conf.pageNo,
					pageSize: conf.pagesize,//每页显示的记录条数，默认为1
					pageList: conf.pageList||[15,20,30,50],//可以设置每页记录条数的列表 
					beforePageText: Obj.get('base.common.easyutil.No'),//页数文本框前显示的汉字 
					afterPageText: Obj.get('base.common.easyutil.page')+ Obj.get('base.common.easyutil.total')+'{pages}'+ Obj.get('base.common.easyutil.page') , 
					displayMsg: Obj.get('base.common.easyutil.Current')+' {from} - {to} '+Obj.get('base.common.easyutil.records')+'   '+Obj.get('base.common.easyutil.total')+' {total} '+Obj.get('base.common.easyutil.records'), 
					onSelectPage:tmpFun
				});
			}else{
				this.loadUrlData();
			}
		}
		var t = 0;
		this.getNum = function(){
			return t;
		}
		this.loadUrlData=function(pageNumber, pageSize,_callback){
			var dg = typeof(conf.eid)=="string"?$("#"+conf.eid):conf.eid;
			dg.datagrid('loading');
			pageNumber=pageNumber||conf.pageNo;
			pageSize=pageSize||conf.pagesize;
			_callback = _callback||function(){};
			if(pageNumber==0){ pageNumber=1;}
			var option ={};
			if(conf.pagination){
				option = dg.datagrid('getPager').pagination("options");
				$(this).pagination('loading');
			}
			option.args = typeof(conf.args) == "string"?$("#"+conf.args).serializeJson():conf.args;
			
			option.args.pageNo = pageNumber;
			option.args.pageSize = pageSize;
			conf.ajaxHandler(option.args, conf.url,function(code,msg,data){
				if(code==0&&data&&data.total>0){
					t = data.total;
					if(data){
						if(data.rows&&data.rows.length>0){
							dg.datagrid("loadData",data);
							_callback.call(dg);
						}
						else if(option.args.pageNo>1) {
							option.args.pageNo--;
							conf.ajaxHandler(option.args, conf.url,function(code,msg,data){
								if(data.rows&&data.rows.length>0)
									dg.datagrid("loadData",data);
								_callback.call(dg);
							});
						}else if(option.args.pageNo<1){
							option.args.pageNo++;
							conf.ajaxHandler(option.args, conf.url,function(code,msg,data){
								if(data&&data.rows&&data.rows.length>0)
									dg.datagrid("loadData",data);

								_callback.call(dg);
							});
						}
					}
				}else{
					if(code==C.AJAX_CODE.LOGIN_REQUIRE){
						$.messager.alert(C.MESSAGE.MSGTITLE,msg,'info',function(){
						    if(window.parent!=undefined){
						    	window.parent.location.href = BASEPATH+"/view/base/main/login";
						    }	
						});
					}else{
						dg.datagrid("loadData",{total:0,rows:[]});
						_callback.call(dg);
					}
				}
				dg.datagrid("loaded");
			});
			if(conf.pagination){
				$(this).pagination('loaded');
			}
		}
		
		/**
		 * 查询分页 具体页码 或 next(下一页) prev(上一页) cur(刷新当前页)
		 * */
		this.pager = function(arg,_callback){
			this.dg.datagrid('loading');
			if(typeof arg=="function"){
				_callback = arg;
				arg = undefined;
			}
			_callback = _callback||function(){};
			pagerTimeOut.call(this,arg,_callback);
			return this;
		}
		var pagerTimeOut = function(arg,_callback){
			if(!conf.pagination){
				return ;
			}
			var dg_ = this.dg;
			var option = dg_.datagrid('getPager').pagination("options");
			if(arg=="prev"){
				dg_.datagrid('getPager').pagination('select', option.pageNumber--,_callback);
			}else if(arg=="next"){
				dg_.datagrid('getPager').pagination('select', option.pageNumber++,_callback);
			}else if(typeof arg=="number"){
				dg_.datagrid('getPager').pagination('select', arg,_callback);
			}else{
				dg_.datagrid('getPager').pagination('select',undefined,_callback);
			}
		}
		
		var configargs = conf.args;
		/**
		 * 更新查询参数  赋值
		 * */
		this.args = function(args){
			if(args){
				conf.args = args;
			}else{
				conf.args = configargs;
			}
			return this;
		}
		/**
		 * 删除行回调 有效返回当前删除页
		 * */
		this.delRow=function(rows){
			var option = this.dg.datagrid('getPager').pagination("options");
			for(var k in rows){
				var index = this.dg.datagrid("getRowIndex",rows[k]);
				this.dg.datagrid("deleteRow",index);
			}
			if((option.total+1)-(option.pageNumber-1)*option.pageSize<=1){
				this.pager("prev");
			}else{
				this.pager();
			}
			return this;
		}
		
		this.loadData = function(arg){
			$(this.dg).datagrid("loadData",arg);
			$(this.dg).parent().height(50+arg.length*35);
			$(this.dg).parent().find(".datagrid-body").height(arg.length*35);
			$(this.dg).closest(".panel-body").height("auto");
		}
		if(conf.createPage!=false){
			this.initPage();
		}else{
			if(conf.args==undefined)
				conf.args = {};
			conf.pagination=false;
			$(this.dg).datagrid(conf);
		}
		if(conf.autoLoad&&conf.pagination){
			this.pager();
		}
		showBTN(undefined,conf);
		return this;
	}
	var showBTN = function (sele,conf){
		//var btnsshow =url.parseURL2JSON(url.getParam("buttons"));
		var pid = (this.app?this.app.pid:"")||url.getParam("pid");
		var flag =url.getParam("showBtnByUser");//showBtnByUser=yes 通过用户获取菜单权限
		var btnsshow = {};
		if(pid!=""&&pid!=null&&indexApp!=undefined){
			btnsshow = indexApp.exec("getButtons",pid);
		}else if(flag=="yes"||indexApp==undefined){
			A.init().success(function(code,msg,data){
				btnsshow=data;
			}).error(function(code,msg,data){
					$.messager.show({
						title:C.MESSAGE.MSGTITLE,
						msg:msg,
						timeout:2000,
						showType:'slide'
					});
			}).sync().post(BASEPATH+"/base/authoriza/func/getFuncByUrl.htm",{url:url.getFunUrl()});
		}
		if($.isEmptyObject(btnsshow)&&(!($.isEmptyObject(indexApp)))){
			btnsshow = indexApp.exec("getButtons");
		}
//		var btnsshow = indexApp.exec("getButtons",pid);
		if(!btnsshow)
			btnsshow={} ;
		var tmp =".datagrid-toolbar";
		if(sele){
			tmp=sele;
		}
		var btns = $(tmp).find("a");
		$.each(btns,function(i,btn){
			if($(btn).attr("sign")=='sign'){
				return true;
			}
			$(btn).attr("sign","sign");
			if($(btn).hasClass("l-btn-display")){
				$(btn).closest("td").hide();
			}
			var opt = $(btn).linkbutton("options");
			var fn = opt.handler;
			opt.handler=null;
			btn.onclick=null;
			var btnurl =opt.url;
			var needRows =opt.needRows;
			var needRow =opt.needRow;
			var isCheck =opt.isCheck;
			opt.onClick=function(e){
				if(needRows){
					var rows = getRows(conf);
					if(rows&&rows.length>0){
						if(isCheck==true){
							$.messager.confirm(C.MESSAGE.MSGTITLE,Obj.get('base.common.easyutil.deletion'),function(r){
							    if (r){
							    	fn(BASEPATH+btnurl,rows);
							    }
							});
						}else{
							fn(BASEPATH+btnurl,rows);
						}
					}
				}else if(needRow){
					var rows = getRow(conf);
					if(rows&&rows.length>0){
						if(isCheck==true){
							$.messager.confirm(C.MESSAGE.MSGTITLE,Obj.get('base.common.easyutil.deletion'),function(r){
							    if (r){
							    	fn(BASEPATH+btnurl,rows[0]);
							    }
							});
						}else{
							fn(BASEPATH+btnurl,rows[0]);
						}
					}
				}else{
					fn(BASEPATH+btnurl);
				}
			}
			$.each(btnsshow,function(i,btnshow){
				if((btnshow.funUrl==BASEPATH+btnurl)||btnshow.link==btnurl){
					$(btn).removeClass("l-btn-display");
					opt.funId=btnshow.funId;
					if(btnshow.funImg&&btnshow.funImg!=""){
						$(btn).find(".l-btn-icon").removeClass().addClass("l-btn-icon").addClass(btnshow.funImg);
					}
					$(btn).closest("td").show();
				}
			});
		});
	}
	function getRow(config){
		var row =  $("#"+config.eid).datagrid("getSelections");
		if(row.length==0||row.length>1){
			$.messager.show({ title:C.MESSAGE.MSGTITLE, msg:Obj.get('base.common.easyutil.record'), timeout:5000, showType:'slide' });
			return [];
		}
		return row;
	}
	function getRows(config){
		var row =  $("#"+config.eid).datagrid("getSelections");
		if(row.length==0){
			using(['messager'],function(){
				$.messager.show({ title:C.MESSAGE.MSGTITLE, msg:Obj.get('base.common.easyutil.record'), timeout:5000, showType:'slide' });
			});
		}
		return row;
	}
	exports.ajaxHandler = function(url,data,upfun,isshow){
		A.init().success(function(code,msg,data){
			if(isshow!=false&&msg!=""){
				$.messager.show({
					title:C.MESSAGE.MSGTITLE,
					msg:msg,
					timeout:2000,
					showType:'slide'
				});
			}
			if(upfun){
				upfun(code,msg,data);
			}
		}).error(function(code,msg,data){
			if(isshow!=false&msg!=""){
				$.messager.show({
					title:C.MESSAGE.MSGTITLE,
					msg:msg,
					timeout:2000,
					showType:'slide'
				});
			}
		}).post(url,data);
	}
	exports.showBTN = function(sele,conf){
		return showBTN(sele,conf);
	}
});
